package com.kate.mall.common.methodhandler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.nimbusds.jose.JWSObject;
import com.kate.mall.common.annotation.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Slf4j
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
    public static final String LOGIN_TOKEN_KEY = "Authorization";

    //1.什么参数接口才解析？
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //如果接口方法参数类型为Integer并且这个参数上有LoginUser注解，那么我们自己解析
        return parameter.getParameterType().isAssignableFrom(Integer.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }
    //2.怎么解析接口参数？
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        //1.从请求头从获取jwt
        String token = request.getHeader(LOGIN_TOKEN_KEY);
        //2.判断非空
        if (StrUtil.isEmpty(token)) {
            return null;
        }
        try {
            //3.从token中解析用户信息
            String realToken = token.replace("Bearer ", "");
            JWSObject jwsObject = JWSObject.parse(realToken);
            String userStr = jwsObject.getPayload().toString();
            log.info("AuthGlobalFilter.filter() user:{}", userStr);
            //3.解析我们jwt ，从jwt中获取用户信息：用户id

            return JSONUtil.parseObj(userStr).get("id")  ;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}